package com.remote.common.tool;

import com.remote.common.util.ImageUtils;
import sun.awt.Win32GraphicsEnvironment;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;

public class MachineTool {
    protected static MachineTool instance;
    private GraphicsDevice screenDevice;
    private Robot robot;
    private Rectangle screenRectangle;
    private Toolkit toolkit;

    public MachineTool() {
        try {
            Win32GraphicsEnvironment environment = new Win32GraphicsEnvironment();
            this.toolkit = Toolkit.getDefaultToolkit();
            this.screenRectangle = new Rectangle(this.toolkit.getScreenSize());
            this.robot = new Robot();
            this.screenDevice = environment.getDefaultScreenDevice();
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }


    public synchronized static MachineTool getInstance() {
        if (instance == null) {
            instance = new MachineTool();
        }
        return instance;
    }

    /**
     * 获取可支持的分辨率
     *
     * @return
     */
    public List<DisplayMode> getSupportableDPIs() {
        DisplayMode[] displayModes = this.screenDevice.getDisplayModes();
        return Arrays.asList(displayModes);
    }

    /**
     * 设置分辨率
     *
     * @param width
     * @param height
     */
    public void setScreenDPI(int width, int height) {
        DisplayMode displayMode1 = this.screenDevice.getDisplayMode();
        this.setScreenDPI(width, height, displayMode1.getBitDepth(), displayMode1.getRefreshRate());
    }

    /**
     * 设置分辨率
     *
     * @param width
     * @param height
     * @param bitDepth
     * @param refreshRate
     */
    public void setScreenDPI(int width, int height, int bitDepth, int refreshRate) {
        DisplayMode displayMode = new DisplayMode(width, height, bitDepth, refreshRate);
        this.setScreenDPI(displayMode);
    }

    /**
     * 设置分辨率
     *
     * @param displayMode
     */
    public void setScreenDPI(DisplayMode displayMode) {
        this.screenDevice.setDisplayMode(displayMode);
    }

    /**
     * @return
     */
    public DisplayMode getScreenDPI() {
        return screenDevice.getDisplayMode();
    }

    public byte[] getScreenSnapshot(int quality) {
        BufferedImage image = this.getRobot().createScreenCapture(this.screenRectangle);
        return ImageUtils.compressedImageAndGetByteArray(image, quality / 100.0f);
    }


    public GraphicsDevice getScreenDevice() {
        return this.screenDevice;
    }

    public Robot getRobot() {
        return this.robot;
    }

    public Toolkit getToolkit() {
        return this.toolkit;
    }


}
